package com.utils;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.io.*;
import java.security.MessageDigest;
import java.util.ArrayList;

/**
 * Created by ShinChven on 2014/10/21.
 */
public class ImageUtil {
    public static final String SCHEME_CONTENT = "content";
    public static final String SCHEME_FILE = "file";

    public static Bitmap zip(Context context, Uri uri,
                             int reqWidth, int reqHeight) throws IOException {

        // First decode with inJustDecodeBounds=true to check dimensions  开启测量模式
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        if (uri.getScheme().equals(SCHEME_CONTENT)) {
            BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options);
        } else if (uri.getScheme().equals(SCHEME_FILE)) {
            BitmapFactory.decodeStream(new FileInputStream(new File(uri.getPath())), null, options);
        } else {
            BitmapFactory.decodeStream(new FileInputStream(new File(uri.getPath())), null, options);
        }


        // Calculate inSampleSize  计算预览比例
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set 按照预览比例载入bitmap
        options.inJustDecodeBounds = false;
        Bitmap bitmap = null;
        if (uri.getScheme().equals(SCHEME_CONTENT)) {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options);
        } else if (uri.getScheme().equals(SCHEME_FILE)) {
            bitmap = BitmapFactory.decodeStream(new FileInputStream(new File(uri.getPath())), null, options);
        }

        bitmap = getRotatedBitmap(context, uri, bitmap);
        return bitmap;
    }

    /**
     * 获取图片存储位置，并根据方向反转图片
     *
     * @param context
     * @param uri
     * @param bitmap
     * @return
     * @throws IOException
     */
    private static Bitmap getRotatedBitmap(Context context, Uri uri, Bitmap bitmap) throws IOException {
        String realPath = null;
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            realPath = uri.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            realPath = cursor.getString(idx);
            cursor.close();
        }

        // 获取方向
        ExifInterface exif = new ExifInterface(realPath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        bitmap = rotateBitmap(bitmap, orientation);
        return bitmap;
    }

    /**
     * 反转图片
     *
     * @param bitmap
     * @param orientation
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }
        try {
            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return bmRotated;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }

    }

    public static Bitmap zip(Resources res, int resId,
                             int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        // 原始大小大于设置大小时，按照设置高宽长的一方为上限进行缩放等比缩放，而不考虑短的一方。inSampleSize反回2就是起这个作用。
        if (height > reqHeight || width > reqWidth) {

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((height / inSampleSize) > reqHeight
                    && (width / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }


    /**
     * 将图片截取为圆角图片
     * @param bitmap 原图片
     * @param ratio 截取比例，如果是8，则圆角半径是宽高的1/8，如果是2，则是圆形图片
     * @return 圆角矩形图片
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float ratio) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, bitmap.getWidth()/ratio,
                bitmap.getHeight()/ratio, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /********
     * 按短边截取正矩形
     * @param bitmap
     * @return
     */
    public static Bitmap getRectBySmall(Bitmap bitmap) {
        int small=0;
        int x=0;
        int y=0;
        if (bitmap.getWidth()>bitmap.getHeight())
        {
            x=(bitmap.getWidth()-bitmap.getHeight())/2;
            y=0;
            small=bitmap.getHeight();
        }else {
            x=0;
            y=(bitmap.getHeight()-bitmap.getWidth())/2;
            small=bitmap.getWidth();
        }


        return Bitmap.createBitmap(bitmap,x,y,small,small);
    }
    /**
     * 保存图片到SD卡
     * @param imagePath
     * @param buffer
     * @throws IOException
     */
    public static void saveImage(String imagePath, byte[] buffer)
            throws IOException {
        File f = new File(imagePath);
        if (f.exists()) {
            return;
        } else {
            File parentFile = f.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            f.createNewFile();
            FileOutputStream fos = new FileOutputStream(imagePath);
            fos.write(buffer);
            fos.flush();
            fos.close();
        }
    }

    /**
     * 从SD卡加载图片
     * @param imagePath
     * @return
     */
    public static Bitmap getImageFromLocal(String imagePath){
        File file = new File(imagePath);
        if(file.exists()){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            file.setLastModified(System.currentTimeMillis());
            return bitmap;
        }
        return null;
    }

    /**
     * Bitmap转换到Byte[]
     * @param bm
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bm){
        ByteArrayOutputStream bas = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bas);
        return bas.toByteArray();
    }

//    /**
//     * 从本地或者服务端加载图片
//     * @return
//     * @throws IOException
//     */
//    public static Bitmap loadImage(final String imagePath,final String imgUrl,final ImageCallback callback) {
//        Bitmap bitmap = getImageFromLocal(imagePath);
//        if(bitmap != null){
//            return bitmap;
//        }else{//从网上加载
//            final Handler handler = new Handler(){
//                @Override
//                public void handleMessage(Message msg) {
//                    if(msg.obj!=null){
//                        Bitmap bitmap = (Bitmap) msg.obj;
//                        callback.loadImage(bitmap, imagePath);
//                    }
//                }
//            };
//
//            Runnable runnable = new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        URL url = new URL(imgUrl);
//                        Log.e("图片加载", imgUrl);
//                        URLConnection conn = url.openConnection();
//                        conn.connect();
//                        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(),8192) ;
//                        Bitmap bitmap = BitmapFactory.decodeStream(bis);
//                        //保存文件到sd卡
//                        saveImage(imagePath,bitmap2Bytes(bitmap));
//                        Message msg = handler.obtainMessage();
//                        msg.obj = bitmap;
//                        handler.sendMessage(msg);
//                    } catch (IOException e) {
//                        Log.e(ImageUtil.class.getName(), "保存图片到本地存储卡出错！");
//                    }
//                }
//            };
//            ThreadPoolManager.getInstance().addTask(runnable);
//        }
//        return null;
//    }



    public static String md5(String paramString) {
        String returnStr;
        try {
            MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
            localMessageDigest.update(paramString.getBytes());
            returnStr = byteToHexString(localMessageDigest.digest());
            return returnStr;
        } catch (Exception e) {
            return paramString;
        }
    }

    /**
     * 将指定byte数组转换成16进制字符串
     *
     * @param b
     * @return
     */
    public static String byteToHexString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex.toUpperCase());
        }
        return hexString.toString();
    }
    /**
     * 将图片保存到相应目录中
     * @param context
     * @param bitmap
     * @param fileName
     */
    public synchronized static void savaImage(Context context,Bitmap bitmap,String dir,String fileName)
    {
        File sdDir = new File("/sdcard/");
        if (sdDir.exists() && sdDir.canWrite()) {
            File uadDir = new File(sdDir.getAbsolutePath() + "/cyej/"+dir);
            uadDir.mkdir();
            if (uadDir.exists() && uadDir.canWrite()) {
                File file = new File(uadDir.getAbsolutePath() + "/" + fileName);
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    Log.e("ImageUtil", "error creating file", e);
                }
                if (file.exists() && file.canWrite()) {
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
                    } catch (FileNotFoundException e) {
                        Log.e("ImageUtil", "ERROR", e);
                    } catch (Exception e) {
                        Log.e("ImageUtil", "ERROR", e);
                    } finally {
                        if (fos != null) {
                            try {
                                fos.flush();
                                fos.close();
                            } catch (IOException e) {
                                // swallow
                            }
                        }
                    }
                } else {
                    Log.e("ImageUtil", "error writing to file");
                }
            }
        }
        recyleBitmapMemory(bitmap);
    }

    /**
     * 从相应目录中获取图片
     * @param fileName
     * @param context
     * @return
     */
    public static Bitmap getImage(String dir,String fileName,Context context)
    {
        File rFile = new File("/sdcard/cyej/"+dir+"/" + fileName);
        if (rFile.exists() && rFile.canRead()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(rFile);
                BitmapDrawable bd=new BitmapDrawable(fis);
                Bitmap newBitmap=bd.getBitmap();
                return newBitmap;
            } catch (IOException e) {
                Log.e("ImageUtil", e.getMessage(), e);
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }
        return null;
    }

    /**
     * 从相应目录中获取图片
     * @param fileName
     * @param context
     * @return
     */
    public static BitmapDrawable getImageDrawable(String dir,String fileName,Context context)
    {
        File rFile = new File("/sdcard/cyej/"+dir+"/" + fileName);
        if (rFile.exists() && rFile.canRead()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(rFile);
                BitmapDrawable bd=new BitmapDrawable(fis);
                return bd;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取相应目录中所有图片
     * @param // fileName
     * @param //context
     * @return
     */
    public static ArrayList<Bitmap> getAllimagefromdir(String dir)
    {
        ArrayList<Bitmap> listbitmap=new ArrayList<Bitmap>();
        File rFile = new File("/sdcard/cyej/"+dir);
        String[] filelist=rFile.list();
        for(int i=0;i<filelist.length;i++)
        {
            File readfile = new File(rFile.getAbsolutePath() + "/" + filelist[i]);
            if(readfile.getName().indexOf(".txt")==-1)
            {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(readfile);
                    BitmapDrawable bd=new BitmapDrawable(fis);
                    Bitmap newBitmap=bd.getBitmap();
                    listbitmap.add(newBitmap);
                } catch (IOException e) {
                    Log.e("ImageUtil", e.getMessage(), e);
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return listbitmap;
    }

    /**
     * 将图片转换成圆角图片
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        final int color  = 0xff424242;
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = 6;

        paint.setAntiAlias(true);
        paint.setColor(color);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0,0, paint);
        return output;
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage
     *            ：源图片资源
     * @param //newWidth
     *            ：缩放后宽度
     * @param //newHeight
     *            ：缩放后高度
     * @return
     */
    public static  Bitmap zoomImage(Bitmap bgimage) {
        int newHeight=0;
        if(bgimage.getWidth()>460)
        {
            newHeight= bgimage.getHeight()/bgimage.getWidth()*460;
        }else
        {
            return bgimage;
        }
        // 获取这个图片的宽和高
        int width = bgimage.getWidth();
        int height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算缩放率，新尺寸除原始尺寸
        float scaleWidth = ((float) 460) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
                matrix, true);
        return bitmap;
    }

    /**
     * 读取本地图片资源
     * @param imgStr  图片路径
     * @param context  Activity
     * @return
     */
    public static BitmapDrawable getBitmapDrawable(String imgStr,Context context)
    {
        Bitmap bmp=null;
        try {
            bmp=BitmapFactory.decodeStream(context.getAssets().open(imgStr));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BitmapDrawable bitmapdraw=new BitmapDrawable(bmp);
        return bitmapdraw;
    }

    /**
     * 把drawable强制转换成Bitmap
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 将bitmap转换成bytes
     * @param bitmap
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bitmap) {
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 回收位图所占的空间大小
     * @param bitmap
     */
    public static void recyleBitmapMemory(Bitmap bitmap)
    {
        if(null!=bitmap&&!bitmap.isRecycled())
        {
            bitmap.recycle();
        }
    }


    //获得带倒影的图片方法
    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){
        // 图片与倒影间隔距离
        final int reflectionGap = 4;
        // 图片的宽度
        int width = bitmap.getWidth();
        // 图片的高度
        int height = bitmap.getHeight();

        Matrix matrix = new Matrix();
        // 图片缩放，x轴变为原来的1倍，y轴为-1倍,实现图片的反转
        matrix.preScale(1, -1);
        // 创建反转后的图片Bitmap对象，图片高是原图的一半。
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap,
                0, height/2, width, height/2, matrix, false);
        // 创建标准的Bitmap对象，宽和原图一致，高是原图的1.5倍。 可以理解为这张图将会在屏幕上显示 是原图和倒影的合体
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Bitmap.Config.ARGB_8888);
        // 构造函数传入Bitmap对象，为了在图片上画图
        Canvas canvas = new Canvas(bitmapWithReflection);
        // 画原始图片
        canvas.drawBitmap(bitmap, 0, 0, null);
        // 画间隔矩形
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, height,width,height + reflectionGap,
                deafalutPaint);
        // 画倒影图片
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
        // 实现倒影渐变效果
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0,
                bitmap.getHeight(), 0, bitmapWithReflection.getHeight()
                + reflectionGap, 0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(shader);

        // Set the Transfer mode to be porter duff and destination in
        // 覆盖效果
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                + reflectionGap, paint);

        return bitmapWithReflection;
    }





}



